// pages/post/create_post/create_post.js
let util = require('../../../utils/content_check.js')
const { formatTime } = require('../../../utils/util.js')
const app = getApp()
var total = [];
var tempFilePaths;
var uid;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imageUrl: [],
    _num:3,
    suggestsList:[],
    isOverdue: null,
    isExchanged: null,
    title: '',
    content: ''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.id){
      // 编辑帖子
      this.setData({
        pageState: 1,
      })
      app.sendGetRequest('/community/cpc/post/'+options.id, (res) => {
        // console.log('编辑帖子', res)
        var data = res.data
        this.setData({
          postId: data.postId,
          title: data.title,
          content: data.content,
        })
      }, (err) => {
        console.log(err.errMsg)
      })
    }else{
      // 创建帖子
      this.setData({
        pageState: 0
      })
    }
  },

  // 选择图片
  chooseImg: function(){
    var that = this;
    wx.chooseImage({
      count: 3, 
      sizeType: ['original', 'compressed'], 
      sourceType: ['album', 'camera'],
      success: function (res) {
        tempFilePaths = res.tempFilePaths
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        that.uploadFile2(tempFilePaths, 0);
        var uploadedImageLists = that.data.imageUrl;
        var totalImages = uploadedImageLists.concat(res.tempFilePaths);
        var aNum = 0;
        if (totalImages.length >= 3) {
          totalImages.length = 3;
          aNum = 1;
        }
        that.setData({
          num: 0,
          addNum: aNum,
          imageUrl: totalImages
        })
      }
    })
  },
  uploadFile2: function (file, i) {//递归调用
    var that = this;
    wx.uploadFile({
      url: app.getHeader() +'/SheQu/uploadWxImg', //仅为
      filePath: file[i],
      name: 'img',
      success: function (res) {
        var obj = new Object();
        obj.ind = i + 1;
        var data = res.data;
        console.info(data);
        obj.src = data;
        console.info("--------------*****-------------------");
        console.info(obj);
        if (!((i + 1) == file.length)) {
          total.push(obj);
          that.uploadFile2(file, i + 1);
        } else {
          total.push(obj);
          that.setData({ perImgSrc: total });
        }
      }
    })
  },
  removeImage: function(e){
    var that = this;
    var currentImageLists = that.data.imageUrl; 
    currentImageLists.splice(e.target.dataset.index,1);
    that.setData({
        imageUrl:currentImageLists
    })
    if(currentImageLists.length < 3 && currentImageLists.length >= 1) {
       that.setData({
            addNum: 0
       })
    } else if(currentImageLists.length == 0) {
       that.setData({
            addNum: 1,
            num: 1
       })
    }
  },
  preImage:function(e){
    var that = this;
    var currentImageUrl = that.data.imageUrl[e.target.dataset.index]
    wx.previewImage({
      current: currentImageUrl, // 当前显示图片的http链接
      urls: that.data.imageUrl // 需要预览的图片http链接列表
    })
  },

  // 输入标题
  onTitleInput: function (e) {
    var title = e.detail.value;
    this.setData({
      title: title
    })
  },
  // 输入内容
  onContentInput: function (e) {
    var content = e.detail.value;
    this.setData({
      content: content
    })
  },

  formSubmit: async function (e){
    var title = this.data.title
    var content = this.data.content
    var time = formatTime(new Date())
    if(!title){
      wx.showToast({
        title: '请输入标题',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(!content){
      wx.showToast({
        title: '请输入内容',
        icon: 'none',
        duration: 2000
      })
      return
    }
    if(this.data.pageState==0){
      var post = {
        title: title,
        content: content,
        postCreateTime: time,
        postUpdateTime: time
      }
      app.sendPostRequest('/community/cpc/post', post, (res) => {
        if(res.code == 200){
          wx.showToast({
            title: '发布成功!',
            icon: 'success',
            duration: 2000
          })
          var postId = res.data
          wx.navigateTo({
            url: '../postDetail/postDetail?id=' + postId
          })
        }else{
          wx.showToast({
            title: '发布失败，请稍后再试！',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }else{
      var post = {
        postId: this.data.postId,
        title: title,
        content: content,
        postUpdateTime: time
      }
      app.sendPutRequest('/community/cpc/post', post, (res) => {
        // console.log('从这里走', res)
        if(res.code == 200){
          // wx.showToast({
          //   title: '编辑成功!',
          //   icon: 'success',
          //   duration: 2000
          // })
          wx.navigateTo({
            url: '../postDetail/postDetail?id=' + this.data.postId
          })
        }else{
          wx.showToast({
            title: '编辑失败，请稍后再试！',
            icon: 'none',
            duration: 2000
          })
        }
      })
    }
  }
    
  
})